﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Studio77.SuperLink.Core;
using Studio77.SuperLink.Entities;
using System.Windows.Threading;
using Studio77.SuperLink.Util;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;

namespace Studio77.SuperLink.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance;

        //combo次数，暂时没用
        public int comboCount;

        /// <summary>
        /// 0-未载入 1-游戏中 2-暂停 3-失败 4-成功
        /// </summary>
        public int gameStatus;
        private object gameStatusSyncObj = new object();
        private string stageCode;
        private DispatcherTimer timer;

        private int leftSeconds;
        private int totalSeonds;

        private int finderCount;
        private int arrangeCount;
        private int clockCount;

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 2;
        List<Image> stars = new List<Image>();

        public GamePage()
        {
            InitializeComponent();
            Instance = this;
            gameStatus = 0;
            this.Loaded += new RoutedEventHandler(GamePage_Loaded);
        }

        void GamePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= new RoutedEventHandler(GamePage_Loaded);

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();
            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    bottomAD.Children.Remove(imgBanner);
                    bottomAD.Children.Add(imgBanner);
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }

        //void adsMogoView1_MogoClickEvent(object sender, EventArgs e)
        //{
        //    //点击广告，暂停游戏
        //    if (gameStatus == 1)
        //    {
        //        timer.Stop();
        //        //显示暂停画面
        //        gameStatus = 2;
        //        this.StoryboardShowPause.Begin();
        //    }
        //}

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            AudioPlayHelper.PlayBackground("background.mp3");
            lock (gameStatusSyncObj)
            {
                if (gameStatus == 0)
                {
                    StartNewGame();
                    //初始化星星
                    foreach (var item in this.stackStar.Children)
                    {
                        stars.Add((Image)item);
                    }
                    this.stackStar.Children.Clear();
                }
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            lock (gameStatusSyncObj)
            {
                if (gameStatus == 1)
                {
                    timer.Stop();
                    //显示暂停画面
                    gameStatus = 2;
                    this.StoryboardShowPause.Begin();
                }
                else if (gameStatus == 2)
                {
                    timer.Start();
                    this.StoryboardHidePause.Begin();
                    this.gameStatus = 1;
                }
                else if (gameStatus == 3 || gameStatus == 4)
                {
                    if (NavigationService.CanGoBack)
                    {
                        NavigationService.GoBack();
                    }
                    else
                    {
                        //返回主界面
                        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
                    }
                }
                e.Cancel = true;
            }

        }

        private void StartNewGame()
        {

            if (StageManager.Instance.CurrentStageType == "1")
            {
                clockCount = 0;
                arrangeCount = 1;
                finderCount = 1;
            }
            else if (StageManager.Instance.CurrentStageType == "2")
            {
                clockCount = 0;
                arrangeCount = 1;
                finderCount = 2;
            }
            else if (StageManager.Instance.CurrentStageType == "3")
            {
                clockCount = 1;
                arrangeCount = 2;
                finderCount = 3;
            }
            UpdateToolUI();


            stageCode = StageManager.Instance.CurrentStageType + "_" + StageManager.Instance.CurrentStageIndex;
            ((CompositeTransform)this.gameCanvas.RenderTransform).TranslateX = -500;
            ((CompositeTransform)this.gridTopBar.RenderTransform).TranslateY = -80;

            //获取关卡信息
            StageInfo sInfo = StageManager.Instance.StageInfos[stageCode];
            this.gameCanvas.StartNewGame(sInfo.Row, sInfo.Column, sInfo.CardChangeRange, sInfo.CardStartIndex, sInfo.ArrangeType);

            //设置关卡的时间信息
            leftSeconds = sInfo.GameSeconds;
            totalSeonds = sInfo.GameSeconds;

            this.gameProcess.Maximum = totalSeonds;
            this.gameProcess.Minimum = 0;
            this.gameProcess.Value = leftSeconds;

            //动画
            this.StoryboardGameCanvasIn.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardGameCanvasIn.Begin();
            this.StoryboardTopBarIn.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardTopBarIn.Completed += new EventHandler(StoryboardTopBarIn_Completed);
            this.StoryboardTopBarIn.Begin();

            //显示游戏开始动画

            SoundManager.PlayEffect(SoundManager.Ready_Go);
        }

        /// <summary>
        /// 更新道具显示
        /// </summary>
        private void UpdateToolUI()
        {
            this.txtFinderCount.Text = finderCount + "";
            this.txtColckCount.Text = clockCount + "";
            this.txtArrangeCount.Text = arrangeCount + "";

            this.btnFinder.IsEnabled = finderCount > 0;
            this.btnReArrange.IsEnabled = arrangeCount > 0;
            this.btnClock.IsEnabled = clockCount > 0;
        }

        void StoryboardTopBarIn_Completed(object sender, EventArgs e)
        {
            //开始计时
            try
            {
                if (timer != null)
                {
                    timer.Stop();
                }
            }
            catch (Exception)
            {
            }

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            //设置为游戏状态
            lock (gameStatusSyncObj)
            {
                gameStatus = 1;
            }

        }

        void timer_Tick(object sender, EventArgs e)
        {
            lock (gameStatusSyncObj)
            {
                if (gameStatus == 1)
                {
                    //游戏中才计时
                    leftSeconds--;
                    //Update ProcessUI
                    this.gameProcess.Value = leftSeconds;
                    if (leftSeconds <= 0 && gameStatus == 1)
                    {
                        //游戏失败Here
                        timer.Stop();
                        gameStatus = 3;

                        //显示游戏失败界面
                        this.StoryboardShowLose.Begin();

                        SoundManager.PlayEffect(SoundManager.Fail);
                    }

                }
            }
        }

        /// <summary>
        /// 完成游戏，由GameCanvas调用
        /// </summary>
        public void WinTheStage()
        {
            lock (gameStatusSyncObj)
            {
                if (gameStatus == 1)
                {
                    SoundManager.PlayEffect(SoundManager.Win);
                    this.gameStatus = 4;
                    this.timer.Stop();
                    //判断是否要显示下一关卡按钮
                    if (StageManager.Instance.CurrentStageIndex + 1 > StageManager.ClassStageCount)
                    {
                        this.btnNextStage.IsEnabled = false;
                    }
                    else
                    {
                        this.btnNextStage.IsEnabled = true;
                    }

                    //显示界面
                    this.StoryboardShowWin.Begin();

                    //判断星星，并存储到数据池中
                    int star = 1;
                    if (leftSeconds >= 25)
                    {
                        star = 3;
                    }
                    else if (leftSeconds >= 15)
                    {
                        star = 2;
                    }
                    if (StageManager.Instance.StageDatas.ContainsKey(stageCode))
                    {
                        if (StageManager.Instance.StageDatas[stageCode].StageLevel < star)
                        {
                            StageManager.Instance.StageDatas[stageCode].StageLevel = star;
                        }
                    }
                    else
                    {
                        StageManager.Instance.StageDatas[stageCode] = new StageData();
                        StageManager.Instance.StageDatas[stageCode].StageLevel = star;
                    }
                    //解锁下个关卡
                    string nextStageCode = StageManager.Instance.CurrentStageType + "_" + (StageManager.Instance.CurrentStageIndex + 1);
                    if (!StageManager.Instance.StageDatas.ContainsKey(nextStageCode))
                    {
                        StageManager.Instance.StageDatas.Add(nextStageCode, new StageData());
                    }

                    StageManager.Instance.SaveStageDatas();

                    //显示星星
                    for (int i = 0; i < star; i++)
                    {
                        this.stackStar.Children.Add(stars[i]);
                    }

                    //星星动画
                    this.StoryboardStarAction.RepeatBehavior = RepeatBehavior.Forever;
                    this.StoryboardStarAction.Begin();
                }
            }
        }

        private void btnFinder_Click(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.Click_Button);
            if (finderCount > 0 && gameStatus == 1)
            {
                if (this.gameCanvas.UseFind())
                {
                    finderCount--;
                    UpdateToolUI();
                }
            }
        }

        private void btnReArrange_Click(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.Click_Button);
            if (arrangeCount > 0 && gameStatus == 1)
            {
                arrangeCount--;
                this.gameCanvas.ReArrange();
                UpdateToolUI();
            }
        }

        private void btnClock_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.Click_Button);
            if (clockCount > 0 && gameStatus == 1)
            {
                clockCount--;
                //增加30秒游戏时间
                this.leftSeconds += 30;
                if (this.leftSeconds > this.totalSeonds)
                {
                    this.leftSeconds = this.totalSeonds;
                }
                this.gameProcess.Value = leftSeconds;
                UpdateToolUI();
            }
        }

        private void NextStage_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            lock (gameStatusSyncObj)
            {
                SoundManager.PlayEffect(SoundManager.Click_Button);
                if (this.gameStatus == 4)
                {
                    StageManager.Instance.CurrentStageIndex = StageManager.Instance.CurrentStageIndex + 1;
                    this.StoryboardHideWin.Begin();
                    this.StoryboardStarAction.Stop();
                    this.stackStar.Children.Clear();
                    StartNewGame();
                }
            }

        }

        private void Restart_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            lock (gameStatusSyncObj)
            {
                SoundManager.PlayEffect(SoundManager.Click_Button);
                bool legal = false;
                if (this.gameStatus == 2)
                {
                    this.StoryboardHidePause.Begin();
                    legal = true;
                }
                if (this.gameStatus == 3)
                {
                    this.StoryboardHideLose.Begin();
                    legal = true;
                }
                if (this.gameStatus == 4)
                {
                    this.StoryboardHideWin.Begin();
                    this.StoryboardStarAction.Stop();
                    legal = true;
                }
                if (legal)
                {
                    StartNewGame();
                    this.stackStar.Children.Clear();
                }
            }
        }

        private void ReturnMenu_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.Click_Button);
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
            else
            {
                //返回主界面
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }

        private void Continue_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            lock (gameStatusSyncObj)
            {
                SoundManager.PlayEffect(SoundManager.Click_Button);
                if (this.gameStatus == 2)
                {
                    timer.Start();
                    this.StoryboardHidePause.Begin();
                    this.gameStatus = 1;
                }
            }
        }

        private void imgBanner_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }
    }
}